JAVA: Summary / Collections 112
3
3
.
.
7
7
C
C
o
o
l
l
l
l
e
e
c
c
t
t
i
i
o
o
n
n
s
s
I
I
n
n
f
f
o
o
Collections hold multiple elements of the same Data Type
the same primitive data type or (like int)
Objects of the same Class (like String)
array is the only Primitive Data Type here. (it is built into language itself)
array is also the only one that can store Primitive Data Types. (other can only store Objects)
String is the only Non-Primitive Data Type here which can be declared using Literal. (String Literal)
All the others are declared by instantiating Object of some Class by calling its Constructor. (they are part of some API)
And they can only store Objects. They can't store Primitive Data Types. (Integer instead of int)
Vector and ArrayList are replacements for array when you need variable number of indexed elements.
INTERFACE
DESCRIPTON
CLASS
THREAD UNSAFE
THREAD SAFE
List
Indexed elements (0, 1, 2, ...)
ArrayList <String>
Vector <String>
Map
Key-value pairs (obj1, obj2, ...)
HashMap <String, Integer>
ConcurrentHashMap <String, Integer>
Set
Unique elements (obj1, obj2, ...)
HashSet <String>
Content
Built-in
array Fixed collection of indexed elements. Values can be Primitive Data Types, Objects or null.
String Fixed collection of indexed characters.
Collections Framework All support variable number of elements.
ArrayList Implements List. Indexed elements can be Objects or null. Not thread safe.
Vector Implements List. Indexed elements can be Objects or null. Thread safe.
HashMap Implements Map. Key-value pairs can be Objects or null. Not thread safe.
ConcurrentHashMap Implements Map. Key-value pairs can be Objects or null. Thread safe.
HashSet Implements Set. Unique elements can be Objects or null.
Iterator Iterate through collection of elements.
Deprecated
Hashtable Variable collection of key-value pairs. Keys & values can only be Objects.
Enumerator Replaced by Iterator.
JAVA: Summary / Collections 113
a
a
r
r
r
r
a
a
y
y
Array can't be resized. To change array size create new one and transfer elements or use ArrayList, Vector, etc.
Array can only contain Elements of the same Data Type: just int, just String, Objects of the same Class.
1D
//DECLARE.
int[] array; //Declared. Used to define scope.
int[] array = null; //Declare empty Array.
int[] array = new int[5]; //Declare Array with default values: 0, 0.0, false, null.
int[] array = {0,1,2,3}; //Declare Array with specific values.
String[] array = {"John", "Lucy"}; //Declare Array os Strings.
//OTHER.
int length = array.length; //Number of elements
System.out.println(Arrays.toString(array)); //Display Array [0, 1, 2, 3]
array[0] = 5; //Modify element at index 0.
int element = array[0]; //Get element at index 0.
2D
//DECLARE.
int[][] array; //Declared. Used to define scope.
int[][] array = null; //Declare empty Array.
int[][] array = new int[2][4]; //Declare Array with default values: 0, 0.0, false, null
int[][] array = { //Declare Array with specific values
{0,1,2,3}, //array[0] = {0,1,2,3} array[0][2] = 2
{4,5}, //array[1] = {4,5} array[1][0] = 4
{6,7,8,9} //array[2] = {6,7,8,9} array[2][3] = 9
};
//OTHER.
int length = array.length; //Number of elements
System.out.println(Arrays.toString(array)); //Display Array [0, 1, 2, 3]
array[2][3] = 90; //Modify element in Array/Row 2 at index 3
int element = array[2][3]; //Get element in Array/Row 2 at index 3
3D
//DECLARE.
String[][][] multyArray =
{
//Table 0
{
{"000","001"}, //Row 0
{"010","011","012","013"} //Row 1
},
//Table 1
{
{"100","101","102","103"}, //Row 0
{"110","111"} //Row 1
}
};
//OTHER.
multyArray[0][1][3] = "013"; //Modify element from Table 0, Row 1, index 3
String element = multyArray[0][1][3]; //Get element from Table 0, Row 1, index 3
JAVA: Summary / Collections 114
S
S
t
t
r
r
i
i
n
n
g
g
[
[
R
R
]
]
String
is Class which contains sequence of characters
is the only Non-Primitive Data Type that can be instantiated using Literal (String Literal)
can also be instantiated using String Class
Declare String
//DECLARE USING STRING LITERAL.
String text = ""; //Empty string.text.length()=0,text.equals("")==true
text = "Hello World"; //Creates String Object with constant text "text".
text = "First line. \n Second line."; //Using escape character '\': \" \t \n \\
text = "Start" + "End"; //Connecting Strings.
//DECLARE USING STRING CONSTRUCTOR.
String text = null; //Calling any function on text throws Exception
text = new String(); //Empty string.
text = new String("text"); //Creates String Object from String Literal
text = new String(new byte[] {'J','o','h','n'}); //Creates String Object from byte array.
//DECLARE USING STRING METHODS.
String text = String.copyTextOf(new char[] {'J','o','h','n'}, 1, 2); //From index 1 take 2: "oh"
text = String.textOf (65 );
text = String.valueOf(65.0);
Modify String
String text = "012345 \n";
String modified = text.toUpperCase (); //Converts all characters to upper case.
modified = text.toLowerCase (); //Converts all characters to lower case.
modified = text.replace ('3', 'A' ); //Replace ALL occurrences of char '3' with 'A'.
modified = text.replaceFirst("23","AB"); //Replace FIRST occurrences of regex "23" with "AB".
modified = text.replaceAll ("23","AB"); //Replace ALL occurrences of regex "23" with "AB".
modified = text.replaceAll ("[\n\r]",""); //Remove all \n and \r characters.
Get Substring
String text = "012345";
String substr = text.substring (2); //Take substring from index 2 till the end. Result is "2345"
substr = text.substring (2,5); //Take substring from index 2 till 5-1=4. Result is "234".
substr = text.trim (); //Erases leading and trailing whitespaces: \t \n
Split String
String text = "zero<->one<->two<->three";
String[] tokens = text.split("<->" ); //Split string around "<->" regex. Gives tokens[0]="one";
tokens = text.split("<->",3); //Create maximum 3 tokens. Gives tokens[2]="two<->three";
tokens = text.split("[135]"); //Split string around 1,3 and 5.
tokens = text.split("/" ); //Split string around '/'.
tokens = text.split("\\." ); //Split string around '.'.
tokens = text.split("\\\\" ); //Split string around '\'.
tokens = "" .split(";" ); //One token is returned resulting in tokens.length=1.
tokens = ";" .split(";" ); //No tokens are returned resulting in tokens.length=0.
JAVA: Summary / Collections 115
A
A
r
r
r
r
a
a
y
y
L
L
i
i
s
s
t
t
ArrayList is the same as Vector with the difference that Vector is thread safe.
ArrayList is Class that contains variable collection of indexed elements. Index is integer starting with 0.
Elements can be inserted at the end or at the existing index (that and subsequent elements are shifted to the right).
When element is removed subsequent elements are shifted to the left.
ArrayList can be used as a replacement for array when you need variable number of elements.
Test.java
import java.util.ArrayList;
import java.util.Iterator;
public class Test {
public static void main (String arg[]) throws Exception {
//DECLARE VECTOR
ArrayList<String> arrayList = new ArrayList<String>();
//ADD ELEMENT
arrayList.add( "John"); //Add element at the end.
arrayList.add(0, "Bill"); //Insert at index 0 (shift higher right)
//GET ELEMENT
String name = arrayList.get (0); //Get value at index 0
//REMOVE ELEMENT
String removed = arrayList.remove(0); //Remove element at index 3 (shift higher left)
arrayList.clear ( ); //Remove all elements
//CHECK FOR ELEMENT
boolean containsValue = arrayList.contains("John");
//SIZE
boolean isEmpty = arrayList.isEmpty();
int size = arrayList.size ();
//ITERATE
Iterator<String> iterator = arrayList.iterator();
while( iterator.hasNext() == true ) {
String value = iterator.next();
System.out.println(value);
iterator.remove(); //Removes current element
}
//DISPLAY
System.out.println(arrayList); //[Bill, John]
}
}
JAVA: Summary / Collections 116
V
V
e
e
c
c
t
t
o
o
r
r
[
[
R
R
]
]
Vector is the same as ArrayList with the difference that Vector is thread safe.
Vector is Class that contains variable collection of indexed elements. Index is integer starting with 0.
Elements can be inserted at the end or at the existing index (that and subsequent elements are shifted to the right).
When element is removed subsequent elements are shifted to the left.
Vector can be used as a replacement for array when you need variable number of elements.
Test.java
import java.util.Vector;
import java.util.Iterator;
public class Test {
public static void main (String arg[]) throws Exception {
//DECLARE VECTOR
Vector<String> vector = new Vector<String>();
//ADD ELEMENT
vector.add( "John"); //Add element at the end of vector.
vector.add (0, "Bill"); //Insert element at index 0 (shift higher right)
//GET ELEMENT
String name = vector.get (0); //Get value at index 0
name = vector.elementAt(0); //Get value at index 0
//REMOVE ELEMENT
String removed = vector.remove(0); //Remove element at index 3 (shift higher left)
vector.clear ( ); //Remove all elements
//CHECK FOR ELEMENT
boolean containsValue = vector.contains("John");
//SIZE
boolean isEmpty = vector.isEmpty();
int size = vector.size ();
//ITERATE
Iterator<String> iterator = vector.iterator();
while( iterator.hasNext() == true ) {
String value = iterator.next();
System.out.println(value);
iterator.remove(); //Removes current element
}
//DISPLAY
System.out.println(vector); //[Bill, John]
}
}
JAVA: Summary / Collections 117
H
H
a
a
s
s
h
h
M
M
a
a
p
p
HashMap is Class that contains variable collection of key-value pairs. Key is unique. Keys & values can be Objects or null.
Test.java
import java.util.HashMap;
import java.util.Collection;
import java.util.Map.Entry;
import java.util.Set;
public class Test {
public static void main (String arg[]) throws Exception {
//DECLARE HASHMAP
HashMap<String, Integer> hashmap = new HashMap<String, Integer>();
//ADD ELEMENT
Integer previousValue = hashmap.put("John", 50); //ADD KEY-VALUE PAIR
previousValue = hashmap.put("Bill", 60); //ADD KEY-VALUE PAIR
//GET ELEMENT
int age = hashmap.get ("John"); //GET VALUE FOR GIVEN KEY
age = hashmap.remove("John"); //REMOVE AND RETURN VALUE
//REMOVE ELEMENT
Integer removed = hashmap.remove("John"); //Remove & return element with key "John"
hashmap.clear(); //REMOVE ALL VALUES
//PROPERTIES
boolean containsKey = hashmap.containsKey ("key");
boolean containsValue = hashmap.containsValue(50);
boolean isEmpty = hashmap.isEmpty();
int size = hashmap.size ();
//GET KEYS / ELEMENTS
Set<String> keys = hashmap.keySet();
Collection<Integer> values = hashmap.values();
Set<Entry<String, Integer>> elements = hashmap.entrySet();
//ITERATE ----------------------------------------------------------------------------------------------
//KEYS.
for (String key : keys ) { System.out.println(key ); }
//VALUES.
for (Integer value : values) { System.out.println(value); }
//ELEMENTS.
for (Entry<String, Integer> element : elements) {
String key = element.getKey();
Integer value = element.getValue();
System.out.println(key + " - " + value);
}
//DISPLAY ----------------------------------------------------------------------------------------------
System.out.println(hashmap); //{John=50, Bill=60}
}
}
JAVA: Summary / Collections 118
C
C
o
o
n
n
c
c
u
u
r
r
r
r
e
e
n
n
t
t
H
H
a
a
s
s
h
h
M
M
a
a
p
p
ConcurrentHashMap is Class that contains variable collection of key-value pairs. Key is unique.
Keys & values can be Objects or null.
Test.java
import java.util.concurrent.ConcurrentHashMap;
import java.util.Collection;
import java.util.Map.Entry;
import java.util.Set;
public class Test {
public static void main (String arg[]) throws Exception {
//DECLARE HASHTABLE
ConcurrentHashMap<String, Integer> concurrentHashMap = new ConcurrentHashMap<String, Integer>();
//ADD ELEMENT
Integer previousValue = concurrentHashMap.put("John", 50); //ADD KEY-VALUE PAIR
previousValue = concurrentHashMap.put("Bill", 60); //ADD KEY-VALUE PAIR
//GET ELEMENT
int age = concurrentHashMap.get ("John"); //GET VALUE FOR GIVEN KEY
age = concurrentHashMap.remove("John"); //REMOVE AND RETURN VALUE
//REMOVE ELEMENT
Integer removed = concurrentHashMap.remove("John"); //Remove & return element
concurrentHashMap.clear(); //REMOVE ALL VALUES
//PROPERTIES
boolean containsKey = concurrentHashMap.containsKey ("key");
boolean containsValue = concurrentHashMap.containsValue(50);
containsValue = concurrentHashMap.contains (50);
boolean isEmpty = concurrentHashMap.isEmpty();
int size = concurrentHashMap.size ();
//GET KEYS / VALUES / ELEMENTS
Set<String> keys = concurrentHashMap.keySet();
Collection<Integer> values = concurrentHashMap.values();
Set<Entry<String, Integer>> elements = concurrentHashMap.entrySet();
//ITERATE ----------------------------------------------------------------------------------------------
//KEYS.
for (String key : keys ) { System.out.println(key ); }
//VALUES.
for (Integer value : values) { System.out.println(value); }
//ELEMENTS.
for (Entry<String, Integer> element : elements) {
String key = element.getKey();
Integer value = element.getValue();
System.out.println(key + " - " + value);
}
//DISPLAY HASHTABLE -------------------------------------------------------------------------------------
System.out.println(concurrentHashMap); //{John=50, Bill=60}
}
}
JAVA: Summary / Collections 119
H
H
a
a
s
s
h
h
S
S
e
e
t
t
[
[
R
R
]
]
HashSet is Class that contains variable collection of unique values. Values can be Objects or null (just one null allowed).
Test.java
import java.util.HashSet;
public class Test {
public static void main (String arg[]) throws Exception {
//DECLARE HASHSET
HashSet<String> hashSet = new HashSet<String>();
//ADD ELEMENT
boolean added = hashSet.add("John"); //Returns true if Set
added = hashSet.add("Bill"); //didn't contain value
//REMOVE ELEMENT
boolean removed = hashSet.remove("John"); //Returns true if Set contained value
hashSet.clear(); //Remove all values
//CHECK FOR ELEMENT
boolean containsValue = hashSet.contains("John");
//SIZE
boolean isEmpty = hashSet.isEmpty();
int size = hashSet.size ();
//ITERATE
for (String value : hashSet) {
System.out.println(value);
}
//DISPLAY HASHSET
System.out.println(hashSet); //{John=50, Bill=60}
}
}
JAVA: Summary / Collections 120
I
I
t
t
e
e
r
r
a
a
t
t
o
o
r
r
[
[
R
R
]
]
Iterator is Class that
is part of Java Collection Framework
is used to iterate through collection of elements (with ability, in some cases, to remove last element returned)
should be used instead of Enumerator (Iterators provide extended functionality & shorter function names)
can't be instantiated (they can only be returned by other collection Classes like Vectors)
Test.java
import java.util.Iterator;
import java.util.Vector;
public class Test {
public static void main (String arg[]) throws Exception {
//CREATE VECTOR.
Vector<String> vector = new Vector<String>();
vector.addElement("John");
vector.addElement("Bill");
vector.addElement("Jack");
//GET ITERATOR.
Iterator<String> iterator = vector.iterator();
//ITERATE.
while( iterator.hasNext() == true ) {
String value = iterator.next();
System.out.println(value);
iterator.remove(); //Removes current element
}
}
}
Console
John
Bill
Jack
JAVA: Summary / Collections 121
D
D
e
e
p
p
r
r
e
e
c
c
a
a
t
t
e
e
d
d
-
-
H
H
a
a
s
s
h
h
t
t
a
a
b
b
l
l
e
e
[
[
R
R
]
]
HashTable is Class that contains variable collection of key-value pairs. Key is unique. Keys & values can only be Objects.
HashTable might be obsolete (replaced by HashMap or ConcurrentHashMap).
Test.java
import java.util.Hashtable;
import java.util.Collection;
import java.util.Map.Entry;
import java.util.Set;
public class Test {
public static void main (String arg[]) throws Exception {
//DECLARE HASHTABLE
Hashtable<String, Integer> hashtable = new Hashtable<String, Integer>();
//ADD ELEMENT
Integer previousValue = hashtable.put("John", 50); //ADD KEY-VALUE PAIR
previousValue = hashtable.put("Bill", 60); //ADD KEY-VALUE PAIR
//GET ELEMENT
int age = hashtable.get ("John"); //GET VALUE FOR GIVEN KEY
age = hashtable.remove("John"); //REMOVE AND RETURN VALUE
//REMOVE ELEMENT
Integer removed = hashtable.remove("John"); //Remove & return element with key "John"
hashtable.clear(); //REMOVE ALL VALUES
//PROPERTIES
boolean containsKey = hashtable.containsKey ("key");
boolean containsValue = hashtable.containsValue(50);
containsValue = hashtable.contains (50);
boolean isEmpty = hashtable.isEmpty();
int size = hashtable.size ();
//GET KEYS / VALUES / ELEMENTS
Set<String> keys = hashtable.keySet();
Collection<Integer> values = hashtable.values();
Set<Entry<String, Integer>> elements = hashtable.entrySet();
//ITERATE ----------------------------------------------------------------------------------------------
//KEYS.
for (String key : keys ) { System.out.println(key ); }
//VALUES.
for (Integer value : values) { System.out.println(value); }
//ELEMENTS.
for (Entry<String, Integer> element : elements) {
String key = element.getKey();
Integer value = element.getValue();
System.out.println(key + " - " + value);
}
//DISPLAY HASHTABLE -------------------------------------------------------------------------------------
System.out.println(hashtable); //{John=50, Bill=60}
}
}
JAVA: Summary / Collections 122
D
D
e
e
p
p
r
r
e
e
c
c
a
a
t
t
e
e
d
d
-
-
E
E
n
n
u
u
m
m
e
e
r
r
a
a
t
t
o
o
r
r
Enumerator is Class that
is used to iterate through collection of elements
is deprecated and should be replaced by Iterator
can't be instantiated but only returned by other Collection Classes like Hashtables
Test.java
import java.util.Enumeration;
import java.util.Hashtable;
public class Test {
public static void main (String arg[]) throws Exception {
//CREATE HASHTABLE.
Hashtable<String, Integer> hashtable = new Hashtable<String, Integer>();
hashtable.put("John", 50);
hashtable.put("Bill", 60);
//GET ENUMERATOR.
Enumeration<String> keys = hashtable.keys();
//ITERATE.
while(keys.hasMoreElements() == true) {
String key = keys.nextElement();
System.out.println(key);
}
}
}
Console
John
Bill